<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';

import { useUserStore } from '@vben/stores';
// import { useAccess } from '@vben/access';
import { getPopupContainer } from '@vben/utils';

import { message, Tooltip } from 'ant-design-vue';

import { employeeQuerySensitiveNoAuth } from '#/api/company/audience';

import { useClinkCall } from './useClinkNew';

interface Props {
  employeeId?: number | string;
  phoneNumber?: number | string;
  size?: string;
  onBusy?: (data: any) => void;
}

const props = withDefaults(defineProps<Props>(), {
  employeeId: undefined,
  phoneNumber: '',
  size: 'small',
  onBusy: () => undefined,
});

const emit = defineEmits<{
  (e: 'busy', mainUniqueId: string): void;
  (e: 'update:calling', value: boolean): void;
}>();
const userStore = useUserStore();
const userInfo = computed(() => {
  return userStore.userInfo;
});
/**
 * 是否自动登录坐席
 * true 页面加载组件时，初始化电话条后自动获取坐席账号并登录。
 * false 页面加载组件时，只初始化电话条，主动点击拨打时才获取坐席账号登录，登录成功
 *       后才自动拨出。
 */
const isAutoLogin = computed(() => {
  // 配置了呼叫坐席账号，并且分配模式为「固定」时，自动登录
  return userInfo.value?.callAllocationType === 1;
});
const isCallOuting = ref(false);
const {
  initializing,
  initialized,
  isLogin,
  loading,
  tip,
  isCalling,
  activePhone,
  // agentInfo,
  login,
  call,
  hangup,
  logout,
  setupClinkToolbar,
} = useClinkCall({
  autoLogin: isAutoLogin.value,
  // 通话事件，获取mainUniqueId
  onBusy: (mainUniqueId: string) => {
    props.onBusy?.(mainUniqueId);
  },
  onIdle: () => {
    // logout();
  },
});

// const currPhoneNumber = ref(props.phoneNumber);
watch(
  () => isLogin.value,
  async (val) => {
    if (val && isCallOuting.value && isActive.value) {
      console.log('==============登录成功后自动呼出');
      if (fullPhone.value) {
        call(fullPhone.value);
      }
      isCallOuting.value = false;
    }
  },
);
watch(
  () => isCalling.value,
  async (val) => {
    emit('update:calling', isCalling.value);
    if (!val && isActive.value && !isAutoLogin.value) {
      logout();
    }
  },
);

const fullPhone = ref<string>();
const isActive = computed(() => activePhone.value === fullPhone.value);

const setDisabled = ref(false);
const buttonDisabled = computed(() => {
  if (!initialized.value) {
    // 电话条插件未初始化成功
    return true;
  }
  // if (!isLogin.value) {
  //   // 电话条初始化成功，未登录成功
  //   return true;
  // }
  if (!isActive.value) {
    if (isCalling.value) {
      // 其它号码按钮呼叫中，需禁用当前按钮
      return true;
    }
    if (loading.value) {
      return true;
    }
  }

  if (setDisabled.value) {
    // 其它禁用
    return true;
  }

  // 无手机号时可呼时禁用
  return !props.phoneNumber;
});

const callTip = ref<string>('');
watch(
  () => tip.value,
  (val) => {
    if (val && isActive.value) {
      // 当前呼叫的手机号的tip结果
      // console.log('activePhone', activePhone.value);
      // console.log('callTip', `${props.phoneNumber}: ${val}`);
      callTip.value = val;

      if (val.includes('禁呼')) {
        setDisabled.value = true;
      }
    }
  },
);
const tipTitle = computed(() => {
  if (callTip.value) {
    return callTip.value;
  }
  if (loading.value) {
    return '初始化中';
  }
  if (!initialized.value) {
    return '呼叫插件安装失败';
  }
  // if (!agentInfo.value) {
  //   return '暂无可用坐席';
  // }
  // if (!isLogin.value) {
  //   return '坐席未登录';
  // }

  if (!props.phoneNumber) {
    return '当前无电话号码，无法呼叫';
  }

  // if (isActive.value) {
  //   return tip.value;
  // }

  return '';
});

const btnText = computed(() => {
  let text = '呼叫';
  if (isActive.value && isCalling.value) {
    text = '挂断';
  }
  return text;
});

// const { hasAccessByCodes } = useAccess();
async function handleClick() {
  if (isActive.value && isCalling.value) {
    hangup();
    isCallOuting.value = false;
  } else {
    // if (hasAccessByCodes(['employee:manager:sensitive'])) {
    loading.value = true;
    isCallOuting.value = true;
    const fullPhoneNumber = await employeeQuerySensitiveNoAuth({
      employeeId: props.employeeId,
      accessPage: 5,
      accessField: 1,
    });
    if (fullPhoneNumber) {
      fullPhone.value = fullPhoneNumber;
      console.log(
        'handleClick fullPhoneNumber',
        isCalling.value,
        isLogin.value,
        isAutoLogin.value,
      );
      if (isLogin.value) {
        loading.value = false;
        call(fullPhoneNumber);
      } else {
        // if (!isAutoLogin.value) {
        if (!isLogin.value) {
          await login(fullPhoneNumber);
        }
      }
    } else {
      message.error('手机号查询失败');
    }
    // } else {
    //   message.warning('您没有权限操作');
    // }
  }
}

onMounted(() => {
  setupClinkToolbar(null);
});

defineExpose({
  loading,
  isLogin,
  isCalling,
  activePhone,
  call,
  hangup,
});
</script>

<template>
  <Tooltip
    :get-popup-container="getPopupContainer"
    placement="leftTop"
    arrow-point-at-center
    :title="tipTitle"
  >
    <ghost-button
      class="flex items-center"
      :class="{ 'btn-success': !isCalling }"
      :loading="initializing || (isActive && loading)"
      :disabled="buttonDisabled"
      :danger="isActive && isCalling"
      :size="size"
      @click="handleClick"
    >
      <template #icon>
        <span class="icon-[ant-design--phone-outlined] mr-[2px]"></span>
      </template>
      {{ btnText }}
    </ghost-button>
  </Tooltip>
</template>

<style lang="scss">
#tinet-toolbar .tinet-header .tinet-status-host .tinet-status {
  display: none !important;
}
</style>
